<?php

use app\home\model\Option as OptionModel;
use think\facade\Cache;

//生成随机数字字符串
function randStr($len)
{
    $chars='0123456789';
    $string='';
    for(;$len>=1;$len--)
    {
        $position=rand()%strlen($chars);
        $string.=substr($chars,$position,1);
    }
    return $string;
}

//重组前端表格数据
function reorganizeTableData($code = 0, $msg = '', $count = 0, $data = [])
{
    $back = [
        'code' => $code,
        'msg'  => $msg,
        'count' => $count,
        'data'  => $data
    ];
    return json($back);
}

//返回json结果
function jsonRes($data = [], $msg = '', $code = 200){
    $res = [
        'code' => $code,
        'msg'  => $msg,
        'data' => $data
    ];
    return json($res);
}

//获取所有字典
function getAllOption()
{
    $list = Cache::get('option_list');
    if (empty($list)) {
        $list = OptionModel::select();
        //缓存1个月
        Cache::set('option_list', $list, 3600 * 24 * 30);
    }
    return $list;
}

//通过名称获取字典
function getOptionByName($list = [], $name)
{
    $option = [];
    //获取一级
    foreach ($list as $key => $item) {
        if ($item['name'] == $name) {
            $option['id'] = $item['id'];
            $option['pid'] = $item['pid'];
            $option['name'] = $item['name'];
            $option['v'] = $item['v'];
            $option['isdel'] = $item['isdel'];
            $option['state'] = $item['state'];
            $option['created'] = $item['created'];
            $option['remarks'] = $item['remarks'];
            $option['order_id'] = $item['order_id'];
            $option['children'] = [];
            break;
        }
    }
    //获取二级
    if (isset($option['id'])) {
        foreach ($list as $key2 => $item2) {
            if ($item2['pid'] == $option['id']) {
                array_push($option['children'], $item2);
            }
        }
    }
    return $option;
}

/**
 * @param $birthday 出生年月日（1992-1-3）
 * @return string 年龄
 */
function countAge($birthday){
    $year=date('Y');
    $month=date('m');
    if(substr($month,0,1)==0){
        $month=substr($month,1);
    }
    $day=date('d');
    if(substr($day,0,1)==0){
        $day=substr($day,1);
    }
    $arr=explode('-',$birthday);

    $age=$year-$arr[0];
    if($month<$arr[1]){
        $age=$age-1;

    }elseif($month==$arr[1]&&$day<$arr[2]){
        $age=$age-1;

    }

    return $age;

}